<template>
  <div class="app-container">
    <div v-show="!dialogInfo.visible && !detailInfo.visible">
      <div class="filter-wrapper">
        <!-- 条件栏 -->
        <NewPageFilter
          v-model:query="filterInfo.query.queryMap"
          :query-more-json="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clear-type="clearType"
          :slip-select-request="slipSelectRequest"
        >
        </NewPageFilter>
      </div>
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-enable>
            <el-button :disabled="!canEnabled" @click="enableds()"
              >启用</el-button
            >
          </template>
          <template v-slot:filter-disable>
            <el-button :disabled="!canDisabled" @click="disableds()"
              >停用</el-button
            >
          </template>
          <template v-slot:filter-uploadFile>
            <el-upload
              :headers="uploadInfo.headers"
              :show-file-list="false"
              :on-error="uploadError"
              :on-success="importProduct"
              :before-upload="beforeProductUpload"
              :action="uploadInfo.action"
            >
              <el-button>导入模板</el-button>
            </el-upload>
          </template>
        </NewPageFilter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>

      <!-- 表格 -->
      <TableContainer
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        v-model:query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-name="scope">
          <span>{{ scope.row.name || '-' }}</span>
        </template>
      </TableContainer>
    </div>
    <PageDialog
      v-if="dialogAuth.visible"
      title="权限模板"
      width="1000px"
      v-model:visible="dialogAuth.visible"
      :bt-list="dialogAuth.btList"
      class="org-dialog"
    >
      <PageFilter
        v-model:query="filterAuth.query"
        :filter-list="filterAuth.list"
      />
      <TableContainer
        :refresh="tableAuth.refresh"
        :init-curpage="tableAuth.initCurpage"
        v-model:data="tableAuth.data"
        :api="tableAuth.api"
        v-model:query="filterAuth.query"
        :field-list="tableAuth.fieldList"
        :handle="tableAuth.handle"
        :highlight-row="true"
        :check-box="false"
        :table-height="300"
        :isDynamic="false"
        @handleEvent="currentAuthTemplate"
      >
      </TableContainer>
    </PageDialog>
    <PageDialog
      v-if="dialogSupplier.visible"
      title="生成供应商"
      width="1000px"
      v-model:visible="dialogSupplier.visible"
      :bt-list="dialogSupplier.btList"
      class="org-dialog"
    >
      <PageForm
        ref="pageFormRef"
        class-name="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="supplierInfo.ref"
        v-model:data="supplierInfo.data"
        :field-list="supplierInfo.fieldList"
        :label-width="supplierInfo.labelWidth"
        :rules="supplierInfo.rules"
      >
      </PageForm>
    </PageDialog>
    <modify
      v-if="dialogInfo.visible"
      :title="dialogInfo.title[dialogInfo.type]"
      v-model:visible="dialogInfo.visible"
      :table-row="dialogInfo.tableRow"
      :type="dialogInfo.type"
      @returnModify="returnModify"
    />
    <defaultSetPreference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      :group-level-show="false"
      @callback="setPreferenceCallback"
    >
    </defaultSetPreference>
    <AdvancedSearch
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:form-data="advancedSearchInfo.data"
      :field-list="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
  </div>
</template>

<script setup name="orgManage">
import {
  getOrgcustomizeListPages,
  enableOrg,
  disableOrg,
  updateOrg,
  autoInsertSupplier,
  updateLockedByOrg,
} from '@/api/base.js'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import { exportTemplateExcel, resetPassword } from '@/api/pub.js'
import { getOrgAuthTemplate } from '@/api/core.js'
import PageForm from '@/components/PageForm/index'
import defaultSetPreference from '@/components/SetPreference/defaultSetPreference'
import Modify from './modify'
import axios from 'axios'
import { ElMessage, ElLoading } from 'element-plus'
const store = useStore()
const { proxy } = getCurrentInstance()
const preferenceInfo = ref({
  visible: false,
})
const advancedSearchInfo = ref({
  visible: false,
  data: {},
})
const slipSelectRequest = ref(true)
const clearType = ref(true)
// 过滤相关配置
const filterInfo = ref({
  flag: 'outside',
  query: {
    customizeUserVO: {},
    queryMap: {},
    queryParams: {
      sort: 'create_time desc',
      searchType: 'org',
    },
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'button',
      label: '新增',
      btType: 'primary',
      event: insert,
      show: proxy.$permission('org:add'),
    },
    {
      type: 'button',
      label: '生成供应商',
      btType: 'primary',
      event: autoInsert,
      show: proxy.$permission('org:autoAdd'),
    },
    {
      type: 'button',
      label: '下载模板',
      event: downloadTemplate,
    },
    { type: 'slot', value: 'uploadFile' },
    {
      type: 'slot',
      label: '启用',
      value: 'enable',
      show: proxy.$permission('org:enabled'),
    },
    {
      type: 'slot',
      label: '停用',
      value: 'disable',
      show: proxy.$permission('org:enabled'),
    },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: proxy.$t('edit'),
        event: update,
        show: proxy.$permission('org:update'),
      },
      {
        label: proxy.$t('enabled'),
        event: enabled,
        show: proxy.$permission('org:enabled'),
        ifRender(row) {
          return row.status === 0
        },
      },
      {
        label: proxy.$t('disabled'),
        event: disabled,
        show: proxy.$permission('org:enabled'),
        ifRender(row) {
          return row.status === 1
        },
      },
      {
        label: proxy.$t('orgAuthTemplate'),
        event: openAuthTemplateDialog,
        show: proxy.$permission('org:auth'),
      },
      {
        label: proxy.$t('resetPassword'),
        event: _resetPassword,
        show: proxy.$permission('org:resetPassword'),
      },
      {
        label: '解锁/锁定',
        event: userLocked,
        show: proxy.$permission('org:locked'),
      },
    ],
  },
})
const uploadInfo = ref({
  action: axios.defaults.baseURL + '/base/orgs/import/excel',
  headers: {
    Authorization: store.state.user.token,
  },
  loading: {},
})
// 弹窗相关
const dialogInfo = ref({
  title: {
    create: '新增机构管理',
    update: '修改机构管理',
  },
  visible: false,
  type: '',
  tableRow: {},
})
const detailInfo = ref({
  visible: false,
  tableRow: {},
})
const dialogAuth = ref({
  visible: false,
  btList: [
    {
      label: '关闭',
      type: '',
      icon: '',
      event: closeAuthDialog,
      show: true,
    },
    {
      label: '保存',
      type: 'primary',
      icon: '',
      disabled: false,
      event: submitAuthTemplate,
      saveLoading: false,
      show: true,
    },
  ],
})
const dialogSupplier = ref({
  visible: false,
  btList: [
    {
      label: '关闭',
      type: '',
      icon: '',
      event: closeAutoInsert,
      show: true,
    },
    {
      label: '保存',
      type: 'primary',
      icon: '',
      disabled: false,
      event: saveAutoInsert,
      saveLoading: false,
      show: true,
    },
  ],
})
const supplierInfo = ref({
  ref: null,
  data: {
    name: '',
    uniformSocialCreditCode: '',
  },
  fieldList: [
    {
      label: '机构名称',
      value: 'name',
      type: 'input',
      required: true,
      maxlength: 64,
    },
    {
      label: '服务范围',
      value: 'serviceScope',
      type: 'select-model',
      code: 'service_scope',
    },
    {
      label: '统一社会信用代码',
      value: 'uniformSocialCreditCode',
      type: 'input',
      maxlength: 30,
    },
    {
      label: '是否建立往来关系',
      value: 'isBuildRelationship',
      type: 'select-model',
      code: 'yes_or_no',
    },
  ],
  labelWidth: '120px',
  rules: {
    name: [{ required: true, message: '请输入机构名称', trigger: 'blur' }],
    // serviceScope: [{ required: true, message: '请选择服务范围', trigger: 'change' }],
  },
})
const tableAuth = ref({
  refresh: 1,
  initCurpage: 1,
  api: getOrgAuthTemplate,
  data: [],
  fieldList: [
    { label: '名称', value: 'name' },
    { label: '编码', value: 'code' },
    { label: '类型', value: 'typeValue' },
    { label: '创建人', value: 'createUserName' },
    { label: '创建时间', value: 'createTime' },
  ],
})
const filterAuth = ref({
  query: {
    nameLike: '',
    type: '',
    sort: 'create_time desc',
  },
  list: [
    {
      type: 'input',
      label: '模板名称',
      value: 'nameLike',
      event: searchAuthTemplate,
      list: 'originList',
    },
    {
      type: 'button',
      label: '搜索',
      btType: 'primary',
      event: searchAuthTemplate,
      show: true,
    },
  ],
})
const orgAuthTemplate = ref('')
const selectOrg = ref('')

let canEnabled = computed(() => {
  return (
    tableInfo.value.selections.length &&
    tableInfo.value.selections.filter((item) => item.status !== 0).length ===
      0 &&
    tableInfo.value.selections.filter(
      (item) => store.getters.userInfo.user.userName === item.adminUsername
    ).length === 0
  )
})
let canDisabled = computed(() => {
  return (
    tableInfo.value.selections.length &&
    tableInfo.value.selections.filter((item) => item.status !== 1).length ===
      0 &&
    tableInfo.value.selections.filter(
      (item) => store.getters.userInfo.user.userName === item.adminUsername
    ).length === 0
  )
})

let obj = ref({
  typeValue: {
    label: '类型',
    value: 'typeValue',
    asValue: 'type',
    componentType: 'select-model',
    code: 'org_type',
    show: false,
    hidden: true,
  },
  statusValue: {
    label: '状态',
    value: 'statusValue',
    asValue: 'status',
    componentType: 'select-model',
    code: 'enabled_type',
    show: false,
    hidden: true,
  },
  lockedValue: {
    label: '是否锁定',
    value: 'lockedValue',
    asValue: 'locked',
    componentType: 'select-model',
    code: 'is_locked',
    show: false,
    hidden: true,
  },
  serviceScopeValue: {
    label: '服务范围',
    value: 'serviceScopeValue',
    asValue: 'serviceScope',
    componentType: 'select-model',
    code: 'service_scope',
    show: false,
    hidden: true,
  },
})
tableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj.value),
})
filterInfo.value.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj.value),
})
onMounted(() => {
  // 非超级管理员需过滤掉内置的slip机构和自身机构(-1)，超级管理员也过滤掉自身机构，防止误操作
  if ('system_admin' !== store.state.user.userInfo.user.type) {
    filterInfo.value.query.queryParams.idNotIn =
      '-1' + ',' + store.state.user.userInfo.user.orgId
  } else {
    filterInfo.value.query.queryParams.idNotIn = '-1'
  }

  // getList()
  getCustomize()
})

function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey: 'baseOrgKey-com.slip.spd.entity.vo.base.BaseOrgVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      proxy.$nextTick(() => {
        let data = res.data
        filterInfo.value.query.customizeUserVO = data
        tableInfo.value.fieldList = proxy.$fn.setFieldList(
          tableInfo.value.fieldList,
          data.detail
        )
        let searchInfo = proxy.$fn.setSearchList(
          filterInfo.value.searchList,
          data.detail
        )
        filterInfo.value.query.queryMap = {
          ...searchInfo.queryMap,
        }

        filterInfo.value.searchList = searchInfo.searchList
        filterInfo.value.searchList.forEach((item) => {
          item.event = search
        })
        filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
          filterInfo.value.query.queryMap
        )
        slipSelectRequest.value = _slipSelectRequest
        tableInfo.value.api = getOrgcustomizeListPages
        getList()
      })
    }
  })
}

function advancedSearchShow() {
  advancedSearchInfo.value.visible = true
}
async function setPreferenceCallback(obj) {
  let vo = proxy.$fn.deepClone(obj.customizeUserVO)
  updateUserCustomize(vo).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}

function advancedSearchCallback(obj) {
  filterInfo.value.query.queryMap = {}
  advancedSearchInfo.value.data = obj.data
  proxy.$nextTick(() => {
    getList()
  })
  clearType.value = !clearType.value
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  search()
}

function search() {
  advancedSearchInfo.value.data = {}
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}

function returnModify() {
  if (dialogInfo.value.tableRow && dialogInfo.value.tableRow.id) {
    getList()
  } else {
    searchOrg()
  }
}
// 获取列表
function getList() {
  tableInfo.value.refresh = Math.random()
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function openAuthTemplateDialog(row) {
  if (store.getters.userInfo.user.userName === row.adminUsername) {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '当前用户不能操作自己的权限模板',
    })
    return
  }
  selectOrg.value = row
  dialogAuth.value.visible = true
  // dialogAuth.value.btList[1].disabled = true;
  filterAuth.value.query.type = row.type
  searchAuthTemplate()
}
function searchOrg() {
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
function downloadTemplate() {
  exportTemplateExcel('org_import').then((res) => {
    if (res) {
      proxy.$fn.parseExcel(res)
    }
  })
}
function submitAuthTemplate() {
  if (orgAuthTemplate.value?.id && selectOrg.value) {
    selectOrg.value.authId = orgAuthTemplate.value.id
  } else {
    selectOrg.value.authId = -1
    selectOrg.value.authName = ''
  }
  let params = { ...selectOrg.value }
  updateOrg(params).then((res) => {
    if (res && res.success) {
      closeAuthDialog()
      getList()
    }
  })
  // else {
  //   proxy.$message({
  //     duration: 3500,
  //     type: "warning",
  //     showClose: true,
  //     message: "请选择权限模板"
  //   });
  // }
}
function _resetPassword(data) {
  if (store.getters.userInfo.user.userName === data.adminUsername) {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '当前用户不能重置自己的密码',
    })
    return
  }
  resetPassword(data.adminUsername)
}
//人员停锁定解锁
function userLocked(data) {
  if (store.getters.userInfo.user.userName === data.adminUsername) {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '当前用户不能为自己解锁/锁定',
    })
    return
  }
  let locked = data.locked == 1 ? 0 : 1
  updateLockedByOrg({ userName: data.adminUsername, locked: locked }).then(
    (resp) => {
      if (resp.success) {
        getList()
      }
    }
  )
}
function closeAuthDialog() {
  dialogAuth.value.visible = false
  orgAuthTemplate.value = {}
}
function searchAuthTemplate() {
  proxy.$nextTick(function () {
    tableAuth.value.initCurpage = Math.random()
    tableAuth.value.refresh = Math.random()
  })
}
function currentAuthTemplate(event, data) {
  switch (event) {
    case 'tableClickRow':
      orgAuthTemplate.value = data
      dialogAuth.value.btList[1].disabled = false
      break
  }
}
// close() {
//   dialogInfo.value.visible = false;
//   this.formInfo.data = {};
// },
//打开新增弹窗
function insert() {
  dialogInfo.value.type = 'create'
  dialogInfo.value.visible = true
  dialogInfo.value.tableRow = {}
}
//打开自动生成弹窗
function autoInsert() {
  supplierInfo.value.data = {
    name: '',
    uniformSocialCreditCode: '',
    type: 'supplier',
  }
  dialogSupplier.value.visible = true
}
function saveAutoInsert() {
  supplierInfo.value.ref.validate((valid) => {
    console.log(valid)
    if (valid) {
      autoInsertSupplier(supplierInfo.value.data).then((resp) => {
        if (resp && resp.success) {
          dialogSupplier.value.visible = false
          getList()
        }
      })
    }
  })
}
//关闭自动生成弹窗
function closeAutoInsert() {
  dialogSupplier.value.visible = false
}
//打开修改弹窗
function update(data) {
  dialogInfo.value.type = 'update'
  dialogInfo.value.visible = true
  dialogInfo.value.tableRow = {
    ...data,
    cities: [data.province, data.city, data.county],
  }
}
//保存
function save() {
  // const dialogInfo = dialogInfo.value;
  // const tableInfo = tableInfo.value;
  // const formInfo = this.formInfo;
  // this.formInfo.ref.validate(valid => {
  //   if (valid) {
  //     let api;
  //     const params = formInfo.data;
  //     params.province = formInfo.data.cities ? formInfo.data.cities[0] : "";
  //     params.city = formInfo.data.cities ? formInfo.data.cities[1] : "";
  //     params.county = formInfo.data.cities ? formInfo.data.cities[2] : "";
  //     const type = dialogInfo.value.type;
  //     if (type === "create") {
  //       api = createOrg;
  //     } else if (type === "update") {
  //       api = updateOrg;
  //     } else {
  //       return;
  //     }
  //     proxy.$handleAPI(type, api, params).then(res => {
  //       if (res.success) {
  //         dialogInfo.visible = false;
  //         tableInfo.refresh = Math.random();
  //         formInfo.data = {};
  //       }
  //     });
  //   }
  // });
}
function modifyCallback(reload) {
  modifyVisible.value = false
  if (reload) {
    tableInfo.value.refresh = Math.random()
  }
}
function enableds() {
  const ids = getIds()
  enableOrg(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function enabled(row) {
  if (store.getters.userInfo.user.userName === row.adminUsername) {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '当前用户不能对自己的状态进行启用和停用',
    })
    return
  }
  const ids = getIds(row)
  enableOrg(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function disableds() {
  const ids = getIds()
  disableOrg(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function disabled(row) {
  if (store.getters.userInfo.user.userName === row.adminUsername) {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '当前用户不能对自己的状态进行启用和停用',
    })
    return
  }
  const ids = getIds(row)
  disableOrg(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function getIds(row) {
  if (row) {
    return [row.id]
  } else {
    return tableInfo.value.selections.map((value) => value.id)
  }
}
function uploadError(err) {
  if (err) {
    ElMessage.error({
      message: '系统错误',
      duration: 3000,
      showClose: true,
    })
  }
  uploadInfo.value.loading.close()
}
function beforeProductUpload(file) {
  //发生请求时打开加载动画
  uploadInfo.value.loading = ElLoading.service({
    fullscreen: true,
    background: 'rgba(255,255,255,.4)',
  })
  let fileType = ['xlsx']
  let fileSize = proxy.$store.state.permission.systemConfig.max_file_size
  let isFileType = fileType.some(
    (type) => file.name.split('.')[file.name.split('.').length - 1] === type
  )
  const isLt = file.size / 1024 / 1024 < fileSize
  if (!isFileType) {
    proxy.$message.error({
      message: `文件格式不正确, 请上传 ${fileType.join(' / ')} 格式文件!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.value.loading.close()
    return false
  }
  if (!isLt) {
    proxy.$message.error({
      message: `上传文件大小不能超过 ${fileSize} MB!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.value.loading.close()
    return false
  }
  return isFileType && isLt
}
function importProduct(resp) {
  uploadInfo.value.loading.close()
  if (resp && resp.success) {
    ElMessage.success({
      duration: 3000,
      showClose: true,
      message: resp.msg,
    })
    getList()
  } else {
    ElMessage.error({
      message: resp.msg,
      duration: 3000,
      showClose: true,
    })
  }
}
</script>

<style>
.org-dialog .el-dialog .el-dialog__body {
  /* height: 355px !important; */
  display: flex;
  flex-direction: column;
}
</style>
